import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login, updateUserInfo, getUserInfo } from '@/api/user'
import { BASEURL } from '@/service/index'

interface LoginParams {
  code: string
  // encryptedData: string,
  // iv: string,
  // rawData: string,
  // signature: string
  // userInfo: {
  //   avatarUrl: string
  //   nickname: string
  // }
}

export const useUserStore = defineStore('userStore', () => {


  const userinfo = ref({
    name: '',
    avatar: '',
    id: '',
    riZhu: '',
    birthday: ''
  })

  const temporaryUserInfo = ref()

  const token = ref('')

  const _login = async () => {
    return new Promise((resolve) => {
      uni.checkSession({
        complete(result) {
          uni.login({
            success: async (result) => {
              uni.showLoading({title: '登录中'})
              const { code: _code, msg, data: _data } = await login(result.code)
              console.log('_data:', _data);
              
              token.value  = _data
              
              const { data: _userInfo } = await getUserInfo()
              console.log('data:', _userInfo);
              if (_userInfo.id) {
                userinfo.value = {..._userInfo, avatar: BASEURL + _userInfo.avatar}
              }
              uni.hideLoading()
              setTimeout(() => resolve(true), 1000)
            }
          })
        },
      })
    })
  }

  const uploadUserInfo = async (params: {
    "avatar": string,
    "name": string,
    riZhu: string,
    birthday: string,
  }) => {
    uni.showLoading({title: '修改中'})
    const { status } = await updateUserInfo(params)
    console.log('status:', status);
    
    if (status === 200) {
      userinfo.value.avatarUrl = params.avatar
      userinfo.value.nickname = params.name
    }
    uni.hideLoading()
    return { status }
  }

  const openUserInfoInputModal = () => {
    uni.showModal({
      title: '提示',
      content: '为了更好的后续服务，需填写个人信息',
      success (res) {
        if (res.confirm) {
          uni.navigateTo({
            url: '/pages/user/setting'
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  }

  return {
    token,
    userinfo, 
    login: _login,
    uploadUserInfo,
    openUserInfoInputModal
  }

}, {
  persist: {
    storage: {
      getItem: (key) => uni.getStorageSync(key),  
      setItem: (key, val) => uni.setStorageSync(key, val)
    }
  },
})


